<?php

/** @see Zend_Controller_Action */

class GpsController extends Zend_Controller_Action
{
	public function listAction()
	{
		$tracksModel = new Default_Model_Tracks();
		$pointsModel = new Default_Model_Points();
		$tracks = $tracksModel->getTracks(Zend_Auth::getInstance()->getIdentity()->id);
		$form = new Default_Form_Gps();
		$form = $form->generate();

		$tracks->setCurrentPageNumber($this->_getParam('page', 1));
		
		$this->view->tracks = $tracks;
		$this->view->form = $form;

		$data = $this->getRequest()->getPost();

		if (!empty($data)) {
			if ($form->isValid($data)) {
				$userId = Zend_Auth::getInstance()->getIdentity()->id;

				$fromTimestamp = new Zend_Date($form->getValue('from'), Zend_Locale::getTranslation(null, 'date', Zend_Locale::ZFDEFAULT));
				$toTimestamp = new Zend_Date($form->getValue('to'), Zend_Locale::getTranslation(null, 'date', Zend_Locale::ZFDEFAULT));
				$fromTimestamp = $fromTimestamp->getTimestamp();
				$toTimestamp = $toTimestamp->getTimestamp();

				$points = $pointsModel->getPoints($userId, $fromTimestamp, $toTimestamp);
				$track = array();
				foreach ($points as $point) {
					$track[] = array(
						'latitude' => $point->lat,
						'longitude' => $point->long,
						'time' => $point->timestamp
					);
				}
				$tracksModel->addTrack($userId, $track);
			}
		}
	}
	
	public function showAction()
	{
		$tracksModel = new Default_Model_Tracks();
		$track = $this->_getParam('track');
		$track = $tracksModel->getTrack($track);
		
		if (!$track) {// || $track->users_id != Zend_Auth::getInstance()->getIdentity()->id)
			throw new Zend_Controller_Action_Exception('Podana sciezka nie istnieje', 404);
		}
		
		$this->view->track = $track;
		
		$this->view->headScript()->appendFile('http://maps.google.com/maps?file=api&v=2.x&key=' . 'ABQIAAAAXV2fkYkA5_uWM3cgORR00hTmm9VICK1RMbTj3iMmsC7G1lLXSRR2sPrwIc3H4JNAsA2zY_IavKU4HQ');
		$this->view->headScript()->appendFile($this->getFrontController()->getRouter()->assemble(array('controller' => 'gps', 'action' => 'show-js', 'track' => strval($track->guid)), 'default', true));
		//$this->view->headScript()->appendFile('/js/google/loadMap.js');
	}
	
	public function showJsAction()
	{
		$tracksModel = new Default_Model_Tracks();
		
		$track = $this->_getParam('track');
		$track = $tracksModel->getTrack($track);
		
		if (!$track) // || $track->users_id != Zend_Auth::getInstance()->getIdentity()->id)
			throw new Zend_Controller_Action_Exception('Podana sciezka nie istnieje', 404);
		
		$this->_helper->layout->disableLayout();
		$center = array();
		
		list($center['x'], $center['y']) = explode(',', trim($track->center, '()'));
		$path = array();
		foreach (explode('),(', trim($track->path, '()')) as $point) {
			$point = explode(',', trim($point, ')('), 2);
			$path[] = array('x' => $point[0], 'y' => $point[1]);
		}
		$track->path = $path;
		
		$this->view->center = $center;
		$this->view->track = $track;
	}
	
	public function statsAction()
	{
		$tracksModel = new Default_Model_Tracks();
		
		$track = $this->_getParam('track');
		$track = $tracksModel->getTrack($track);
		
		if (!$track) // || $track->users_id != Zend_Auth::getInstance()->getIdentity()->id)
			throw new Zend_Controller_Action_Exception('Podana sciezka nie istnieje', 404);
		
		$path = array();
		$length = array();
		foreach (explode('),(', trim($track->path, '()')) as $point) {
			$point = explode(',', trim($point, ')('), 2);
			
			$end = end($path);
			if ($end)
				$length[] = 
					round(sqrt(69.1 * pow(end($end) - end($point), 2) + // x
						69.1 * pow(reset($end) - reset($point), 2) * cos(end($point) / 57.3)) * // y
						1609.344); // w metrach!
			$path[] = $point;
		}
		$time = explode(',', trim($track->time, '{}'));
		$start = reset($time);
		$speed = array();
		$last = 0;
		foreach ($time as $i => &$t) {
			if (!isset($length[$i])) {
				continue;
			}
			$t -= $start;
			
			if ($t <= 0.001)
				$speed[] = 0;
			else// if ($length[$i] / $t <= 20)
				$speed[] = round(($length[$i] / ($t - $last)) * 3.6, 2);
			$last = $t;
			$t = round($t/60);
		}
		$speed2 = array();
		$speedStep = ceil(count($speed)/200);
		for ($i = 0; $i < count($speed); $i += $speedStep) {
			$speed2[] = array_sum(array_slice($speed, $i, $speedStep))/$speedStep;
		}
		$speed = $speed2; unset($speed2);
		
		$speedAvg = round(array_sum($speed)/count($speed));
		
		
		$this->view->speed = (str_replace(array("\n", "\t"), array('&amp;', ''), '<img src="http://chart.apis.google.com/chart?cht=lc
			chs=640x400
			chd=t:' . implode(',', $speed) . '
			chxt=x,y
			chxl=0:|0min|' . $time[round(count($time)/2)] . 'min|' . end($time) . 'min|1:|0|' . $speedAvg . 'kmph|' . round(max($speed)/2) . 'kmph|' . round(max($speed)) . 'kmph
			chxp=0,0,50,100|1,0,' . min(round($speedAvg/max($speed)*100), 50) . ',' . max(round($speedAvg/max($speed)*100), 50) . ',100" />'));
		
		$lengthSum = array();
		foreach ($length as $i => $l) {
			$lengthSum[] = array_sum(array_slice($length, 0, $i));
		}
		/*
		$this->view->speed = (str_replace(array("\n", "\t"), array('&amp;', ''), '<img src="http://chart.apis.google.com/chart?cht=lc
			chs=640x400
			chd=t:' . implode(',', $speed) . '
			chxt=x,y
			chxl=0:|0min|' . $time[round(count($time)/2)] . 'min|' . end($time) . 'min|1:|0|' . round(array_sum($speed)/count($speed)) . 'kmph|' . round(max($speed)) . 'kmph
			chxp=0,0,50,100|1,0,' . round(array_sum($speed)/count($speed)) . ',' . round(max($speed)) . '" />'));*/
	}
}